package com.imu.purse.modules.sys.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.imu.common.exception.ErrorDesc;
import com.imu.common.exception.ErrorUtil;
import com.imu.common.utils.PhoneUtil;
import com.imu.common.utils.R;
import com.imu.common.validator.Assert;
import com.imu.constant.Constant;
import com.imu.purse.common.utils.ShiroUtils;
import com.imu.purse.modules.sms.SMSAliMessage;
import com.imu.purse.modules.sms.SMSCache;
import com.imu.purse.modules.sms.SMSMessage;
import com.imu.purse.modules.sys.entity.SysUserEntity;
import com.imu.purse.modules.sys.service.SysUserService;
import com.imu.purse.modules.sys.service.SysUserTokenService;
import com.xiaoleilu.hutool.util.RandomUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * 登录相关
 * 
 * @author sunhongwei
 * @email sunhongwei@gmail.com
 * @date 2017-03-23 15:22:06
 */
@RestController
public class SysLoginController extends AbstractController 
{
	/**
	 * 验证码
	 */
	@RequestMapping("captcha")
	@SuppressWarnings("deprecation")
	public void captcha(HttpServletResponse response)throws ServletException, IOException 
	{
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//生成文字验证码
		String text = producer.createText();
		//生成图片验证码
		BufferedImage image = producer.createImage(text);
		//保存到shiro session
		ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}
	
	/**
	 * 登录
	 */
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public Map<String, Object> login(String username, String password, String captcha, String smsmessage)throws IOException
	{
		//本项目已实现，前后端完全分离，但页面还是跟项目放在一起了，所以还是会依赖session
		//如果想把页面单独放到nginx里，实现前后端完全分离，则需要把验证码注释掉(因为不再依赖session了)
		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
		if(!captcha.equalsIgnoreCase(kaptcha)){
			return R.error("验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(username);

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) 
		{
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0)
		{
			return R.error("账号已被锁定,请联系管理员");
		}

		//验证手机验证码
		SMSMessage.Type messageType = SMSMessage.Type.LOGIN;
		if(messageType == null){
			return R.error("类型不匹配");
		}
		try{
			String a = cache.findCode(messageType.getType(), user.getMobile());
			if(StringUtils.isEmpty(a) || !a.equals(smsmessage))
				return R.error("手机验证码输入错误");
		}
		catch (Exception e)
		{
			return R.error("手机验证码校验失败");
		}

		//生成token，并保存到数据库
		R r = sysUserTokenService.createToken(user.getUserId());
		if(StrUtil.isNotBlank(this.version))
		{
			r.put("version", this.version.trim()); //保存版本信息
		}
		
		return r;
	}
	
	/**
	 * 退出
	 */
	@RequestMapping(value = "/sys/logout", method = RequestMethod.POST)
	public R logout() 
	{
		sysUserTokenService.logout(getUserId());
		return R.ok();
	}

	@GetMapping("message")
	public R message(HttpServletRequest request, String username) {
		Assert.isBlank(username, "用户名不能为空", 0);

		SysUserEntity sysUserEntity =sysUserService.queryByUserName(username);
		if(null == sysUserEntity || null == sysUserEntity.getMobile())
		{
			return R.error(0, "不存在此用户或未绑定手机号");
		}
		String phone = null; // 手机号
		if (!PhoneUtil.isXPhone(phone = String.valueOf(sysUserEntity.getMobile()))) {
			return R.error(0, "用户绑定的手机号不正确");
		}

		SMSMessage.Type messageType = SMSMessage.Type.LOGIN;

		if (messageType == null) {
			return ErrorUtil.errorMesg(request, ErrorDesc.TYPE_ERR);
		}


		String code = cache.check(phone);

		if (StrUtil.isBlank(code)) {
			return ErrorUtil.errorMesg(request, ErrorDesc.ACODE_ERR);
		} else if (!code.equalsIgnoreCase("0")) {
			return ErrorUtil.errorMesg(request, ErrorDesc.ACODE_SEND);
		}

		try {
			SMSMessage message = new SMSMessage();
			message.setPhone(phone);
			message.setAuthcode(RandomUtil.randomNumbers(Constant.ACODE_LEN));
			message.setType(messageType);
			smsAliMessage.send(message); // 发送验证码
		} catch (Exception e) {
			return ErrorUtil.errorMesg(request, ErrorDesc.ACODE_SED_ERR);
		}

		return R.ok(1);
	}
	
	/***
	 * 系统版本
	 */
	@Value("${xchat.version}")
    private String version;
	
	@Autowired
	private Producer producer;
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysUserTokenService sysUserTokenService;

	/*
	 * @Autowired private SendSMS sms;
	 */

	@Autowired
	private SMSCache cache;

	@Autowired
	private SMSAliMessage smsAliMessage;
}
